package com.andaily.web.controller.mobile;

import com.andaily.domain.dto.user.RegisterUserDTO;
import com.andaily.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author Shengzhao Li
 */
@Controller
@RequestMapping("/register")
public class RegisterController {

    private UserService userService;

    private Validator registerUserValidator;

    @RequestMapping(method = RequestMethod.GET)
    public String setupForm(ModelMap model) {
        RegisterUserDTO dto = new RegisterUserDTO();
        model.addAttribute("registerUserDTO", dto);
        return "mobile_register";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String submit(@ModelAttribute("registerUserDTO") RegisterUserDTO registerUserDTO, BindingResult result, ModelMap model) {
        registerUserValidator.validate(registerUserDTO, result);
        if (result.hasErrors()) {
            return "mobile_register";
        }
        userService.saveRegisterUser(registerUserDTO);
        model.put("email", registerUserDTO.getEmail());
        return "redirect:register/success";
    }

    @RequestMapping("success")
    public String registerSuccess() {
        return "mobile_register_success";
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    @Qualifier(value = "registerUserValidator")
    public void setRegisterUserValidator(Validator registerUserValidator) {
        this.registerUserValidator = registerUserValidator;
    }
}
